package 双指针或滑动窗口.长度为k子数组中的最大和2461;

import java.util.HashMap;

public class Solution {
    public long maximumSubarraySum(int[] nums, int k) {
        long ans = 0, s = 0;
        HashMap<Integer, Integer> cnt = new HashMap<>();

        for (int i = 0; i < nums.length; i++) {
            s += nums[i];
            if (cnt.containsKey(nums[i])) {
                cnt.put(nums[i], cnt.get(nums[i]) + 1);
            } else {
                cnt.put(nums[i], 1);
            }

            int left = i - k + 1;
            if (left < 0) {
                continue;
            }

            if (cnt.size() == k) {
                ans = Math.max(ans, s);
            }

            int out = nums[left];
            s -= out;
            int c = cnt.get(out);
            if (c > 1) {
                cnt.put(out, c - 1);
            } else {
                cnt.remove(out);
            }

        }

        return ans;
    }
}
